package com.zhh.controller;

import com.zhh.common.ServerResponse;
import com.zhh.dto.LoginDto;
import com.zhh.jwt.JWTUtil;
import com.zhh.jwt.Token;
import com.zhh.pojo.TbUser;
import com.zhh.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;


/**
 * @author
 */
@RestController
public class UserController {

    final static Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private JWTUtil jwtUtil;

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public ServerResponse login(String username, String password, HttpServletResponse response) {
        //MD5加密
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        String newToken = jwtUtil.sign(username, md5Pass);
        Set<String> roles = userService.getRoles(username);
        LoginDto dto = new LoginDto();
        dto.setToken(newToken);
        if (!roles.isEmpty()){
            dto.setRole(roles.iterator().next());
        }
        response.setHeader("Authorization", newToken);
        return ServerResponse.createBySuccess(dto);
    }


    /**
     * 登出
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "/user/logout", method = RequestMethod.GET)
    public ServerResponse logout(HttpServletRequest req) {
        log.info("用户登出");
        String token = req.getHeader("Authorization");
        return userService.logout(token);
    }



}
